package com.ruoyi.web.controller.api;

import java.util.List;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.estate.Complaint;
import com.ruoyi.system.service.estate.IComplaintService;

/**
 * 用户投诉API Controller
 */
@RestController
@RequestMapping("/api/complaint")
public class ComplaintApiController extends BaseController {
    
    @Autowired
    private IComplaintService complaintService;
    
    /**
     * 获取用户投诉列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Complaint complaint) {
        startPage();
        try {
            // 设置当前用户ID
            Long userId = SecurityUtils.getUserId();
            complaint.setResidentId(userId);
            // 只设置删除标志为未删除
            complaint.setDelFlag("0");
            List<Complaint> list = complaintService.selectComplaintList(complaint);
            return getDataTable(list);
        } catch (Exception e) {
            // 用户未登录或会话过期，返回空列表
            return getDataTable(new ArrayList<>());
        }
    }
    
    /**
     * 获取投诉详情
     */
    @GetMapping("/{complaintId}")
    public AjaxResult getInfo(@PathVariable("complaintId") Long complaintId) {
        try {
            // 获取当前用户ID
            Long userId = SecurityUtils.getUserId();
            
            // 获取投诉信息
            Complaint complaint = complaintService.selectComplaintById(complaintId);
            
            // 验证是否是当前用户的投诉
            if (complaint != null && complaint.getResidentId().equals(userId)) {
                return AjaxResult.success(complaint);
            } else {
                return AjaxResult.error("您无权查看此投诉信息");
            }
        } catch (Exception e) {
            return AjaxResult.error("获取投诉详情失败");
        }
    }
    
    /**
     * 提交投诉
     */
    @PostMapping("/submit")
    public AjaxResult submit(@RequestBody Complaint complaint) {
        try {
            // 设置当前用户ID
            Long userId = SecurityUtils.getUserId();
            complaint.setResidentId(userId);
            
            // 不在这里设置residentName，让ComplaintServiceImpl中的逻辑处理
            // 只处理匿名标志
            if (complaint.getIsAnonymous() != null && "1".equals(complaint.getIsAnonymous())) {
                // 匿名投诉，设置为"匿名用户"
                complaint.setResidentName("匿名用户");
            } else {
                // 确保isAnonymous字段为"0"
                complaint.setIsAnonymous("0");
                // 不设置residentName，让service层查询住户信息并设置
            }
            
            // 提交投诉
            int rows = complaintService.insertComplaint(complaint);
            return toAjax(rows);
        } catch (Exception e) {
            return AjaxResult.error("提交投诉失败: " + e.getMessage());
        }
    }
    
    /**
     * 撤销投诉
     */
    @PutMapping("/cancel/{complaintId}")
    public AjaxResult cancel(@PathVariable("complaintId") Long complaintId) {
        try {
            // 记录日志
            System.out.println("API调用: 撤销投诉, ID=" + complaintId);
            
            // 获取当前用户ID
            Long userId = SecurityUtils.getUserId();
            System.out.println("当前用户ID: " + userId);
            
            // 获取投诉信息
            Complaint complaint = complaintService.selectComplaintById(complaintId);
            
            // 验证投诉是否存在
            if (complaint == null) {
                System.out.println("投诉不存在: 投诉ID=" + complaintId);
                return AjaxResult.error("投诉不存在");
            }
            
            // 验证是否是当前用户的投诉
            if (!complaint.getResidentId().equals(userId)) {
                System.out.println("无权撤销投诉: 投诉ID=" + complaintId + ", 投诉所属用户ID=" + complaint.getResidentId() + ", 当前用户ID=" + userId);
                return AjaxResult.error("您无权撤销此投诉");
            }
            
            // 验证投诉状态是否为待处理
            if (!"0".equals(complaint.getComplaintStatus())) {
                System.out.println("投诉状态不允许撤销: 投诉ID=" + complaintId + ", 当前状态=" + complaint.getComplaintStatus());
                return AjaxResult.error("只能撤销待处理的投诉");
            }
            
            // 调用撤销投诉服务方法
            int result = complaintService.cancelComplaint(complaint);
            System.out.println("撤销投诉结果: 投诉ID=" + complaintId + ", 结果=" + result);
            
            return toAjax(result);
        } catch (Exception e) {
            System.out.println("撤销投诉异常: 投诉ID=" + complaintId + ", 错误信息=" + e.getMessage());
            e.printStackTrace();
            return AjaxResult.error("撤销投诉失败: " + e.getMessage());
        }
    }
    
    /**
     * 评价投诉
     */
    @PutMapping("/evaluate")
    public AjaxResult evaluate(@RequestBody Complaint complaint) {
        try {
            // 获取当前用户ID
            Long userId = SecurityUtils.getUserId();
            
            // 获取投诉信息
            Complaint original = complaintService.selectComplaintById(complaint.getComplaintId());
            
            // 验证是否是当前用户的投诉且状态为已处理
            if (original != null && original.getResidentId().equals(userId) && "2".equals(original.getComplaintStatus())) {
                // 设置评价信息
                original.setSatisfaction(complaint.getSatisfaction());
                original.setEvaluation(complaint.getEvaluation());
                return toAjax(complaintService.evaluateComplaint(original));
            } else {
                return AjaxResult.error("您无权评价此投诉或投诉未处理完成");
            }
        } catch (Exception e) {
            return AjaxResult.error("评价投诉失败");
        }
    }
} 